const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const Console = require('./console.js');

// 主机IP，绑定到0.0.0.0让服务器监听所有接口
const hostname = '0.0.0.0';
// 监听端口
const port = 3000;

// 创建HTTP服务器
const server = http.createServer((req, res) => {
    Console.log('Step1: 接收到的请求为：', req.url);
    // 获取请求路径，不考虑查询参数
    const pathname = url.parse(req.url).pathname;

    // 根据分隔符拆分请求路径，并过滤掉空字符串
    const urlParts = pathname.split('/').filter(d => !!d);
    // 如果路径片段数组为空，则指定默认值
    urlParts.length === 0 && urlParts.push('api', 'default');
    // 如果第一个元素不是'api'，则添加'api'。(指定后续的文件位置在api目录下)
    urlParts[0] !== 'api' && urlParts.unshift('api');

    // 将路径片段转换为文件路径，并加上文件后缀
    const filePath = path.join(__dirname, path.join(...urlParts)) + '.js';

    Console.log(`Step2: 将请求路径转换为文件路径：${filePath}`);

    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , skipDefaultRetMsg');
    res.setHeader('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    res.setHeader('Content-Type', 'application/json;charset=utf-8');
    res.on('finish', () => {
        Console.log('===> Response has finished.');
    });

    // 每次请求前都清除模块缓存
    try {
        const cacheKey = require.resolve(filePath);
        delete require.cache[cacheKey];
    } catch (e) {
        // 不做操作
    }

    let resData;

    // 动态加载对应模块并执行模块中的 `getData` 方法
    try {
        resData = require(filePath).getData(req.method);
        res.statusCode = 200;
    } catch (error) {
        resData = require(path.join(__dirname, 'api', 'error.js')).getData();
        res.statusCode = 500;
    } finally {
        res.end(resData);
        Console.success(`Step3: 请求结束`);
    }
});

// 监听端口并启动服务器
server.listen(port, hostname, () => {
    console.log('========================================');
    console.log(`Server running at http://${hostname}:${port}/`);
    console.log('========================================');
});
